package com.algorithm;

public class BinarySearch {

    public static void main(String[] args) {
        int[] m0 = {0, 2, 2, 3, 4, 5, 5, 7, 8, 9, 10, 12};
        System.out.println(searchMin(m0, -332));
    }


    public static int search(int[] arrays, int target) {

        if (arrays == null || arrays.length == 0) {
            return -1;
        }

        int start = 0;
        int end = arrays.length - 1;
        int middle;

        while (start <= end) {

            middle = (start + end) >> 1;
            if (arrays[middle] == target) {
                return middle;
            }

            if (arrays[middle] > target) {
                end = middle - 1;
            } else {
                start = middle + 1;
            }

        }

        return -1;
    }

    public static int searchMin(int[] arrays, int target) {
        if (arrays == null || arrays.length == 0) {
            return -1;
        }
        int start = 0;
        int end = arrays.length - 1;
        int middle;
        while (start <= end) {
            middle = (start + end) >> 1;
            if (arrays[middle] == target) {
                return middle;
            }
            if (arrays[middle] > target) {
                end = middle - 1;
            } else {
                start = middle + 1;
            }
        }
        middle = (start + end) >> 1;

        return arrays[Math.max(middle, 0)];
    }


}
